package com.iiiu.payment.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库配置类
 * 启动时验证数据库连接并打印表信息
 */
@Slf4j
@Component
public class DatabaseConfig implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        testDatabaseConnection();
        printTableNames();
    }

    /**
     * 测试数据库连接
     */
    private void testDatabaseConnection() {
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                log.info("✅ 数据库连接成功！");
                log.info("数据库URL: {}", connection.getMetaData().getURL());
                log.info("数据库驱动: {}", connection.getMetaData().getDriverName());
                log.info("数据库版本: {}", connection.getMetaData().getDatabaseProductVersion());
            } else {
                log.error("❌ 数据库连接失败！");
            }
        } catch (SQLException e) {
            log.error("❌ 数据库连接异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 打印数据库中的所有表名
     */
    private void printTableNames() {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables(connection.getCatalog(), null, "%", new String[]{"TABLE"});
            
            List<String> tableNames = new ArrayList<>();
            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                tableNames.add(tableName);
            }
            
            if (tableNames.isEmpty()) {
                log.info("📋 数据库中暂无表");
            } else {
                log.info("📋 数据库中的表列表 (共{}个表):", tableNames.size());
                for (int i = 0; i < tableNames.size(); i++) {
                    log.info("  {}. {}", i + 1, tableNames.get(i));
                }
            }
            
        } catch (SQLException e) {
            log.error("❌ 获取数据库表信息失败: {}", e.getMessage(), e);
        }
    }
}